package de.jowadroid.timekeeping;

import java.lang.reflect.Field;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import de.jowadroid.timekeeping.database.DataProvider;
import de.jowadroid.timekeeping.database.DatabaseController;
import de.jowadroid.timekeeping.database.IDataAccessListener;
import de.jowadroid.timekeeping.database.IWorktimeDataAccess;
import de.jowadroid.timekeeping.database.JoWaDroidTimekeepingContentProvider;
import de.jowadroid.timekeeping.database.Timestamp;
import de.jowadroid.timekeeping.tempdata.DataEvaluater;
import de.jowadroid.timekeeping.tempdata.IDataEvaluater;

public class MainActivity extends Activity {
	
	
	/** Indicates whether given timestamp is start or stop working timestamp. True means start.*/
	private boolean isNextTimestampStart;
	private TableLayout table;
	private Button startStopButton;
	private IWorktimeDataAccess dataAccess;
	private IDataEvaluater dataEvaluater;

	OnClickListener startStopListener = new OnClickListener() {
		
		public void onClick(View v) {
			saveCurrentTimestamp();
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getOverflowMenu();
		setContentView(R.layout.activity_main);	
		table = (TableLayout) findViewById(R.id.worktimeTable);
		
		dataEvaluater = new DataEvaluater();
		
		dataAccess = new DataProvider(getBaseContext());
		dataAccess.addDataAccessListener( (IDataAccessListener)dataEvaluater);
		
		startStopButton = (Button) findViewById(R.id.startStopTimer);
		startStopButton.setOnClickListener(startStopListener);
		boolean lastEntryStartTime = dataAccess.isLastEntryStartTime();
		if (lastEntryStartTime) {
			isNextTimestampStart = false;
			startStopButton.setText(R.string.stopString);
		} else {
			isNextTimestampStart = true;
			startStopButton.setText(R.string.startString);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.actionbar_top, menu);
		return true;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dataAccess.removeDataAccessListener((IDataAccessListener)dataEvaluater);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		
		case R.id.menu_settings:
			saveCurrentTimestamp();
			break;
		case R.id.showAllData:
			//TODO_Johannes Sinvoll machen
			getData();
			break;
		case R.id.deleteWorktimesTable:
			deleteAllData();
			break;			
		case R.id.updateTableEntry:
			updateOneWorktimeTableEntryById(0); 
		}
		return true;
	}
	
	private void updateOneWorktimeTableEntryById(int id) {
		Cursor dataRow = getOneWorktimeTableEntryById(id);
		if (dataRow != null) {
			//Start test code
			int columnIdxTimestamp = dataRow.getColumnIndex(DatabaseController.COLUMN_TIMESTAMP);
			String timestamp = dataRow.getString(columnIdxTimestamp);
			int timestampNum = Integer.parseInt(timestamp);
			timestampNum += 5;
			//end test code
			Uri updateUri = Uri
					.parse(JoWaDroidTimekeepingContentProvider.WORKTIMES_TABLE_URI
							+ "/" + id);
			
			ContentValues values = new ContentValues();
			values.put(DatabaseController.COLUMN_TIMESTAMP, Integer.toString(timestampNum));
			
			int updatedRows = getContentResolver().update(updateUri, values, null, null);
			String toastText;
			if (updatedRows == 1) {
				toastText = "Table row "+id+" was successfully updated.";
			} else {
				toastText = "Update of table row "+id+" failed.";
			}
			Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show();
		}
	}
	
	//TODO is this method needed
	/**
	 * Returns a cursor on the table row with the given id. worktimes table is
	 * accessed.
	 * 
	 * @param id
	 *            Table row id
	 * @return The cursor or null if given id wasn't found
	 */
	private Cursor getOneWorktimeTableEntryById(int id) {
		String[] tableColumns = { DatabaseController.COLUMN_WEEK_NUMBER,
				DatabaseController.COLUMN_TIMESTAMP,
				DatabaseController.COLUMN_START_STOP };

		// get all table entries
		Uri readUri = Uri
				.parse(JoWaDroidTimekeepingContentProvider.WORKTIMES_TABLE_URI
						+ "/" + id);
		Cursor dataRow = getContentResolver().query(readUri, tableColumns,
				null, null, null);

		return dataRow;
	}

	private void deleteAllData() {
		String message;
		if (dataAccess.deleteAllData()) {
			message = "Data successfully deleted";
		} else {
			message = "Nothing deleted";
		}
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		//delete displayed data
		startStopButton.setText(R.string.startString);
		isNextTimestampStart = true;
		deleteDisplayedWorktimeData();

	}
	
	private void getData() {

		String[] tableColumns = {	
			DatabaseController.COLUMN_WEEK_NUMBER, 
			DatabaseController.COLUMN_TIMESTAMP,
			DatabaseController.COLUMN_START_STOP};
		
		//get all table entries
		Cursor worktimeData =  getContentResolver().query(
			JoWaDroidTimekeepingContentProvider.WORKTIMES_TABLE_URI, 
			tableColumns, null, null, null);
		
		if (worktimeData != null) {
			int columnIdxWeekNumber = worktimeData.getColumnIndex(DatabaseController.COLUMN_WEEK_NUMBER);
			int columnIdxTimestamp = worktimeData.getColumnIndex(DatabaseController.COLUMN_TIMESTAMP);
			int columnIdxStartStop = worktimeData.getColumnIndex(DatabaseController.COLUMN_START_STOP);
			
			deleteDisplayedWorktimeData();
			
			while ( worktimeData.moveToNext() ) {
				String weekNumber = worktimeData.getString(columnIdxWeekNumber);
				String timestamp = worktimeData.getString(columnIdxTimestamp);
				boolean isStartTime = Boolean.parseBoolean(worktimeData.getString(columnIdxStartStop));
				int textColor;
				if (isStartTime) {
					textColor = Color.GREEN;
				} else {
					textColor = Color.RED;
				}
					
				//create a new table row with two elements for wekkname and worktime
				TableRow row = new TableRow(this);
							
				TextView weekTV = new TextView(this);
				weekTV.setLayoutParams( new TableRow.LayoutParams(1) );
				weekTV.setText(weekNumber);
//				weekTV.setGravity(Gravity.LEFT);
//				weekTV.setPadding(20, 0, 0, 0);
				
				TextView worktimeTV = new TextView(this);
				worktimeTV.setText(timestamp);
				worktimeTV.setLayoutParams( new TableRow.LayoutParams(1) );
				worktimeTV.setTextColor(textColor);
//				worktimeTV.setGravity(Gravity.RIGHT);
//				worktimeTV.setPadding(0, 0, 20, 0);

				//add the two text fields and the row to the table layout
				row.addView(weekTV);
				row.addView(worktimeTV);
				table.addView(row);
				
				//add the seperating line
				TableRow borderRow = new TableRow(this);
				borderRow.setBackgroundResource(R.drawable.horizontal_line);			
				table.addView(borderRow);
			}
			
		    worktimeData.close();
		} else {
			Toast.makeText(this, "Retrieving data from database failed", Toast.LENGTH_SHORT).show();
		}
	}

	private void deleteDisplayedWorktimeData() {
		//-1 because heading row shouldn't become deleted
		int deleteViewCount = table.getChildCount()-1;
		for (int i = deleteViewCount; i > 0; i--) {
			table.removeViewAt(i);
		}
	}
	
	/**
	 * Triggers save of current timestamp and toggles the start stop flag
	 */
	private void saveCurrentTimestamp() {
		long timestamp = System.currentTimeMillis() / 1000;
		//Add Data into database
		if ( dataAccess.saveTimestamp(new Timestamp(timestamp, isNextTimestampStart) ) ) {
			Toast.makeText(this, "Saving successful", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "Save failed", Toast.LENGTH_SHORT).show();
		}		
		toggleStartStopFlag();
	}
	
	private void toggleStartStopFlag() {
		if (isNextTimestampStart == true) {
			isNextTimestampStart = false;
			startStopButton.setText(R.string.stopString);
		} else {
			isNextTimestampStart = true;
			startStopButton.setText(R.string.startString);
		}
	}

	private void getOverflowMenu() {
	     try {
	        ViewConfiguration config = ViewConfiguration.get(this);
	        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
	        if(menuKeyField != null) {
	            menuKeyField.setAccessible(true);
	            menuKeyField.setBoolean(config, false);
	        }
	     } catch (Exception e) {
	    	 e.printStackTrace();
	     }
	}
}
